<?php

namespace app\middleware;

use app\model\SystemMenu;
use app\model\SystemUser;
use app\Request;
use app\traits\UserTrait;
use think\helper\Arr;

class SystemOperLog
{
    protected $username;
    protected $method;
    protected $router;
    protected $service_name;
    protected $ip;
    protected $request_data;
    protected $response_data;
    protected $response_code;
    protected $created_by;
    protected $created_at;
    protected $source;

    /** @var Request $midReq 当前请求对象 */
    protected $request;

    use UserTrait;

    public function handle(Request $request, \Closure $next)
    {
        $this->request = $request;
        $response = $next($request);
        $methods = ['POST', 'PUT', 'DELETE'];
        if (in_array($request->method(), $methods)) {
            $this->log();
        }
        return $response;
    }

    protected function log()
    {
        $this->initData();
        $insert = [
            'username' => $this->username,
            'method' => $this->method,
            'router' => $this->router,
            'service_name' => $this->service_name,
            'ip' => $this->ip,
            'request_data' => $this->request_data,
            'created_by' => $this->created_by,
            'created_at' => date('Y-m-d H:i:s'),
            'source' => $this->source,
        ];
        \app\model\SystemOperLog::create($insert);
    }

    protected function initData()
    {
        if (strpos($this->request->url(), 'system/user/login') !== false) {
            $this->username = $this->request->post('username');
            $this->service_name = '用户登录';
        } else {
            $this->username = SystemUser::withTrashed()->find($this->getUid())->value('username');
            $this->service_name = $this->getServiceName();
        }
        $this->method = $this->request->method();
        $this->router = $this->request->url();
        $this->ip = $this->request->ip();
        $this->request_data = $this->getRequestData();
        $this->created_by = $this->getUid();
        $this->source = $this->request->header('device_type');
    }

    public function getRequestData(): string
    {
        $data = [];
        if ($this->request->method() == 'POST') {
            $data = $this->request->post();
        }
        if ($this->request->method() == 'PUT') {
            $data = $this->request->put();
        }
        if ($this->request->method() == 'DELETE') {
            $data = $this->request->DELETE();
        }
        if (isset($data['password'])) {
            $data['password'] = md5($data['password']);
        }
        return json_encode($data, 320);
    }

    public function getServiceName(): string
    {
        $requestUrl = preg_replace('/\d+/', '', $this->request->url());
        return Arr::get($this->serviceNameMaps(), $requestUrl) ?? '';
        $url = explode('/', $this->request->url());
        $menuCodeItem = [];
        foreach ($url as $item) {
            ($item && !intval($item)) && $menuCodeItem[] = $item; //过滤掉空和路径上的数字
        }
        $menuCode = join(':', $menuCodeItem);
        return SystemMenu::where(['code' => $menuCode])->value('name', '');
    }

    protected function serviceNameMaps(): array
    {
        return [
            '/system/user/login' => '用户登录',
            '/system/user/save' => '新增用户',
            '/system/user/update' => '编辑用户',
            '/system/user/modifyPassword' => '修改密码',
            '/system/user/updateInfo' => '更新用户',
            '/system/user/delete' => '删除用户',
            '/system/user/logout' => '退出登录',
            '/system/menu/save' => '新增菜单',
            '/system/menu/update' => '编辑菜单',
            '/system/role/save' => '新增角色',
            '/system/role/update' => '编辑角色',
            '/system/role/menuPermission' => '分配权限',
            '/system/role/delete' => '删除角色',
            '/system/device/save' => '新增设备',
            '/system/device/update' => '编辑设备',
            '/system/device/delete' => '删除设备',
            '/system/device/batchUpdateStatus' => '批量更新设备状态',
            '/system/stock/save' => '新增仓库',
            '/system/stock/update' => '编辑仓库',
            '/system/stock/delete' => '删除仓库',
            '/system/stock/userAssign' => '分配仓库人员',
            '/system/stockSetting/save' => '系统配置管理',
            '/system/stockSetting/copy' => '系统配置复制',
        ];
    }
}